<template>
  <div>
    <el-table
      class="cash"
      :data="tableData"
      style="width: 100%"
      show-summary
      :summary-method="getSummaries"
      size="mini"
      max-height="550">
      <el-table-column
        prop="symbol"
        label="币种"
        width="100"
      >
      </el-table-column>
      <el-table-column
        prop="type"
        label="类型"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="security"
        label="保证金"
      >
      </el-table-column> -->
      <el-table-column
        prop="openPrice"
        label="开仓均价"
      >
      </el-table-column>
      <el-table-column
        prop="multiple"
        label="合约倍数"
      >
      </el-table-column>
      <el-table-column
        prop="buyAmount"
        label="合约张数"
      >
      </el-table-column>
      <el-table-column
        prop="price"
        label="合约单价(usdt)"
        width="120"
      >
      </el-table-column>
      <el-table-column
        prop="buyDate"
        label="购买日期"
      >
      </el-table-column>
      <el-table-column
        prop="nowPrice"
        label="当前价格"
      >
        <template slot-scope="scope">
          <el-tag size="small" :type="Number(scope.row.nowPrice) >= Number(scope.row.buyPrice) ? 'success' : 'danger'">{{ scope.row.nowPrice }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="nowDate"
        label="当前时间"
        width="150"
      >
      </el-table-column>
      <el-table-column
        prop="percent"
        label="收益率"
      >
        <template slot-scope="scope">
          <el-tag size="small" :type="Number(scope.row.percent) >= 0 ? 'success' : 'danger'">{{ scope.row.percent }}%</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="usd"
        label="收益金额"
      >
        <template slot-scope="scope">
          <el-tag size="small" :type="Number(scope.row.usd) >= 0 ? 'success' : 'danger'">{{ scope.row.usd }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="usdt"
        label="收益金额(usdt)"
        width="120"
      >
        <template slot-scope="scope">
          <el-tag size="small" :type="Number(scope.row.usd) >= 0 ? 'success' : 'danger'">{{ (scope.row.usd * scope.row.nowPrice).toFixed(2) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="zero"
        label="预计强平仓价"
        width="120"
      >
      </el-table-column>
      <el-table-column
        label="操作"
        width="100">
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="deleteRow(scope.$index, scope.row, tableData)"
            type="text"
            size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row style="margin-top: 10px;text-align:right;">
      <el-col :span="2" :offset="18">
        <el-button size="small" type="success" @click="dialogVisible = true">新增</el-button>
      </el-col>
      <el-col :span="2">
        <el-upload
          action="#"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
          :http-request="handleUpload"
          :show-file-list="false"
        >
          <el-button size="small" type="primary" :loading="importLoading">导入</el-button>
        </el-upload>
      </el-col>
      <el-col :span="2">
        <el-button size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
      </el-col>
    </el-row>
    <el-dialog
      title="币种添加"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose">
      <el-form :model="form" :rules="rules" ref="symbolForm">
        <el-form-item label="币种:" prop="symbol" :label-width="formLabelWidth">
          <el-input v-model="form.symbol"></el-input>
        </el-form-item>
        <el-form-item label="类型:" prop="type" :label-width="formLabelWidth">
          <el-select v-model="form.type" placeholder="类型">
            <el-option label="开多" value="开多"></el-option>
            <el-option label="开空" value="开空"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="保证金:" prop="security" :label-width="formLabelWidth">
          <el-input v-model="form.security"></el-input>
        </el-form-item> -->
        <el-form-item label="开仓均价:" prop="openPrice" :label-width="formLabelWidth">
          <el-input v-model="form.openPrice"></el-input>
        </el-form-item>
        <el-form-item label="合约倍数:" prop="multiple" :label-width="formLabelWidth">
          <el-input v-model="form.multiple"></el-input>
        </el-form-item>
        <el-form-item label="购买张数:" prop="buyAmount" :label-width="formLabelWidth">
          <el-input v-model="form.buyAmount"></el-input>
        </el-form-item>
        <el-form-item label="单价:" prop="price" :label-width="formLabelWidth">
          <el-input v-model="form.price"></el-input>
        </el-form-item>
        <el-form-item label="购买日期:" prop="buyDate" :label-width="formLabelWidth">
        <el-date-picker type="date" placeholder="购买日期" v-model="form.buyDate" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="预计强平仓价:" :label-width="formLabelWidth">
          <el-input v-model="form.zero"></el-input>
        </el-form-item>
        <el-form-item label="备注:" :label-width="formLabelWidth">
          <el-input v-model="form.remarks"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveSymbol" :loading="modalLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import XLSX from 'xlsx'
  import db from '../../store/database'
  import { getMarketUSDT } from '../../api/huobi';
  import { getFormatDate } from '../../utils'
  export default {
    data() {
      return {
        electron: process.versions.electron,
        name: this.$route.name,
        node: process.versions.node,
        path: this.$route.path,
        platform: require('os').platform(),
        vue: require('vue/package.json').version,
        amountId: null,
        tableData: [],
        dialogVisible: false,
        form: {
          symbol: '',
          openPrice: '',
          multiple: '',
          buyAmount: '',
          price: '',
          buyDate: '',
          zero: '',
          remarks: ''
        },
        modalLoading: false, 
        importLoading: false, 
        exportLoading: false, 
        rules: {
          symbol: [
            { required: true, message: '请输入币种', trigger: 'blur' },
            { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
          ],
          openPrice: [
            { required: true, message: '请输入开仓均价', trigger: 'blur' }
          ],
          multiple: [
            { required: true, message: '请输入合约倍数', trigger: 'blur' }
          ],
          buyAmount: [
            { required: true, message: '请输入合约张数', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入合约单价', trigger: 'blur' }
          ],
          buyDate: [
            { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
          ],
        },
        formLabelWidth: '120px'
      };
    },
    async created() {
      await this.init()
      this.amountId = setInterval(async () => {
        this.init()
      }, 2 * 1000)
    },
    methods: {
      async deleteRow(index, row, rows) {
        await db.contractUSD.where('id').equals(row.id).delete()
        rows.splice(index, 1);
      },
      async init() {
        const [tickets, coins] = await Promise.all([getMarketUSDT(), db.contractUSD.toArray()])
        
        const ticketsKeys = {} // 转化为map
        tickets.forEach((item) => {
          // 'EHT-USD'
          ticketsKeys[item.contract_code.split('-')[0].toLowerCase()] = item
        })
        const coinList = []
        coins.forEach((item) => {
          const find = ticketsKeys[item.symbol]
          const cha = Number(find.close) - Number(item.openPrice)
          const nowDate = getFormatDate()
          let percent = (cha / find.close * 100 * item.multiple).toFixed(2) // 收益率
          let usd = (item.buyAmount * item.price / item.openPrice * cha / find.close).toFixed(4) // 收益金额
          if (item.type === '开空') {
            percent = (-percent).toFixed(2)
            usd = (-usd).toFixed(4)
          }
          if (find) {
            // TODO 消息提醒
            coinList.push({
              ...item,
              nowPrice: find.close,
              nowDate,
              percent,
              usd,
            })
          }
        })
        await db.contractUSD.bulkPut(coinList) // 更新数据
        const nowCoinList = await db.contractUSD.toArray()
        this.tableData = nowCoinList;
      },
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '合计';
          } else if (column.property === 'usdt') {
            const values = data.reduce((carry, item) => Number(item.usd * item.nowPrice) + carry, 0)
            sums[index] = values.toFixed(2)
          } else {
            sums[index] = ''
          }
        });

        return sums;
      },
      handleClose() {
        this.$refs.symbolForm.resetFields()
        this.dialogVisible = false
      },
      saveSymbol() {
        this.$refs.symbolForm.validate(async (valid) => {
          if (valid) {
            this.modalLoading = true
            await db.contractUSD.add({
              ...this.form,
              buyDate: getFormatDate(this.form.buyDate, 'Y-m-d')
            })
            this.dialogVisible = false
            this.modalLoading = false
            return true
          } 
          return false
        });
      },
      handleUpload({ file }) {
        this.importLoading = true
        const reader = new FileReader();
        reader.onload = async (e) => {
          const excelData = XLSX.read(e.target.result, {
            type: 'binary'
          });
          // excelData.SheetNames[0]是获取Sheets中第一个Sheet的名字
          // excelData.Sheets[Sheet名]获取第一个Sheet的数据
          const data = XLSX.utils.sheet_to_json(excelData.Sheets[excelData.SheetNames[0]]);
          if (data.length) {
            const nowData = data.map((item) => ({
              symbol: item['币种'],
              type: item['类型'],
              openPrice: item['开仓均价'],
              multiple: item['合约倍数'],
              buyAmount: item['购买张数'],
              price: item['单价'],
              buyDate: item['购买时间'],
              zero: item['预计强平仓价'],
            }))
            await db.contractUSD.clear() // 清空上次数据
            await db.contractUSD.bulkAdd(nowData)
            this.$message.success('导入成功')
          } else {
            this.$message.error('导入失败')
          }
          this.importLoading = false
        };
        reader.readAsBinaryString(file);
      },
      handleExport() {
        const tableData = this.tableData.map((item) => ({
          '币种': item.symbol,
          '类型': item.type,
          '开仓均价': item.openPrice,
          '合约倍数': item.multiple,
          '购买张数': item.buyAmount,
          '单价': item.price,
          '购买时间': item.buyDate,
          '预计强平仓价': item.zero,
        }))
        const sheet = XLSX.utils.json_to_sheet(tableData);
        this.openDownloadDialog(this.sheet2blob(sheet), `coin-contract-usd${getFormatDate(null, 'Y_m_d_H_i_s')}.xlsx`);
        this.$message.success('导出成功')
      },
      sheet2blob(sheet, sheetName) {
        sheetName = sheetName || 'sheet1';
        const workbook = {
          SheetNames: [sheetName],
          Sheets: {}
        };
        workbook.Sheets[sheetName] = sheet; // 生成excel的配置项

        const wopts = {
          bookType: 'xlsx', // 要生成的文件类型
          bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
          type: 'binary'
        };
        const wbout = XLSX.write(workbook, wopts);
        const blob = new Blob([this.s2ab(wbout)], {
          type: 'application/octet-stream'
        }); // 字符串转ArrayBuffer
        
        return blob;
      },
      s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      },
      openDownloadDialog(url, saveName) {
        if (url instanceof Blob) {
          url = URL.createObjectURL(url); // 创建blob地址
        }
        const aLink = document.createElement('a');
        aLink.href = url;
        aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
        let event;
        if (window.MouseEvent) {
          event = new MouseEvent('click');
        } else {
          event = document.createEvent('MouseEvents');
          event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
        }
        aLink.dispatchEvent(event);
      }
    },
    watch: {

    },
    destroy() {
      clearInterval(this.amountId)
    }
  };
</script>

<style scoped>
 
</style>
